package com.admin.contorl;

import java.io.IOException;
import java.net.URL;
import java.util.Map;

import com.admin.common.AlertUtils;
import com.admin.common.FileUtils;
import com.admin.common.Show;
import com.admin.entity.adminList;

import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

public class RegisterViewControl {
    @FXML
    private TextField txt_id;
    @FXML
    private PasswordField txt_password;
    @FXML
    private PasswordField txt_confirmPassword;
    @FXML
    private TextField txt_userName;
    @FXML
    private Button btn_register;
    @FXML
    private Button btn_back;

    public void register() {
        String id = txt_id.getText();
        String password = txt_password.getText();
        String userName = txt_userName.getText();
        String confirmPassword = txt_confirmPassword.getText();
        if (id.isEmpty() || password.isEmpty() || confirmPassword.isEmpty()) {
            AlertUtils.showDialog("提示", "请输入完整信息");
            return;
        }
        adminList admin;
        if (password.equals(confirmPassword)) {
            admin = new adminList(id, password, userName);
            Map<String, adminList> adminMap = FileUtils.readObject("com\\admin\\admin.txt");
            if (adminMap.containsKey(id)) {
                AlertUtils.showDialog("提示", "管理员已存在");
            } else {
                adminMap.put(id, admin);
                FileUtils.writeObject("com\\admin\\admin.txt", adminMap);
                AlertUtils.showDialog("提示", "注册成功");
                try {
                    Stage stage = (Stage) btn_register.getScene().getWindow();
                    URL url = getClass().getResource("/com/admin/view/IndexView.fxml");
                    Show.show(stage, url, "登录页面");
                } catch (IOException e) {
                    e.printStackTrace();
                }
                for (adminList a : adminMap.values()) {
                    System.out.println("账户：" + a.getid() + " 密码： " + a.getPassword());
                }
            }
        } else {
            AlertUtils.showDialog("提示", "密码不一致");
        }
    }

    public void back() {
        System.out.println("返回登录页面");
        try {
            Stage stage = (Stage) btn_back.getScene().getWindow();
            URL url = getClass().getResource("/com/admin/view/IndexView.fxml");
            Show.show(stage, url, "登录页面");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
